# coding: utf8
from django.template.base import Library
from django.utils.html import format_html
import re

register = Library()

@register.simple_tag(takes_context=True)
def pagination_render(context, paginator):
	'''分页渲染'''
	# 上下文获取当前访问的url(包含查询参数)
	# 分析, 然后去除page参数 ?page=1 或 &page=1
	full_url = context.request.get_full_path()
	for page_param in re.findall("([?|&]page=\d+)", full_url):
		full_url = full_url.replace(page_param, '')
	full_url = full_url+'&page=%d' if '?' in full_url else full_url+'?page=%d'

	navigation = '''
	<nav aria-label="Page navigation">
	  <ul class="pagination">
	  %s
	  </ul>
	</nav>
	'''
	navigation_lis = ''

	# 上一页
	if paginator.has_previous():
		navigation_lis += '''
		<li>
		  <a href="%s" aria-label="Previous">
			<span aria-hidden="true">&laquo;</span>
		  </a>
		</li>''' % (full_url % paginator.previous_page_number())

	# 每页
	for pg in paginator.paginator.page_range:
		if paginator.number == pg:
			navigation_lis += '''
			<li class="active">
				<span>
					%d
					<span class="sr-only">(current)</span>
				</span>
			</li>
			''' % (pg)
		else:
			navigation_lis += '''
			<li>
				<a href="%s">
					%d
				</a>
			</li>
			''' % (full_url % pg,pg)

	# 下一页
	if paginator.has_next():
		navigation_lis += '''
		<li>
		  <a href="%s" aria-label="Next">
			<span aria-hidden="true">&raquo;</span>
		  </a>
		</li>
		''' % (full_url % paginator.next_page_number())


	return format_html(navigation % navigation_lis)